package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ApAuthorFeign;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.service.ApUserFanService;
import com.usian.user.service.ApUserFollowService;
import com.usian.user.service.ApUserService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Autowired
    private ApUserFanService apUserFanService;

    @Autowired
    private ApUserService apUserService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //参数校验
        if (dto.getArticleId() == null || dto.getAuthorId() == null || dto.getOperation() == null || dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApAuthor apAuthor = apAuthorFeign.findById(dto.getAuthorId());
        //判断作者信息是否为空
        if (apAuthor != null){

            //判断是关注还是取消关注
            ApUser apUser = AppThreadLocalUtils.getUser();
            Integer userId = null;
            if (apUser != null){
                userId =apUser.getId();
            }
            if (dto.getOperation() == 0){
                //关注
                boolean follows = follows(userId, dto.getAuthorId(), apAuthor.getName(),dto.getArticleId());
                if (!follows){
                    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
                }
            }else if (dto.getOperation() == 1){
                //取消关注
                cancelFollows(userId,dto.getAuthorId(),apAuthor.getName());
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消关注
     *
     * @param userId
     * @param followId
     * @param followName
     */
    public void cancelFollows(Integer userId,Integer followId,String followName){
        //删除follow表
        this.remove(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId)
                .eq(ApUserFollow::getFollowId, followId));

        //删除fan表
        apUserFanService.remove(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId)
                .eq(ApUserFan::getFansId, userId));
    }

    /**
     * 关注
     *
     * @param userId
     * @param followId
     * @param followName
     * @return
     */
    public boolean follows(Integer userId,Integer followId,String followName,Long articleId){
        boolean flag = true;

        //查询数据是否从在
        ApUserFollow userFollow = this.getOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId)
                .eq(ApUserFollow::getFollowId, followId));
        if (userFollow == null){
            ApUserFollow apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(userId);
            apUserFollow.setFollowId(followId);
            apUserFollow.setFollowName(followName);
            apUserFollow.setLevel((short)1);
            apUserFollow.setIsNotice(true);
            apUserFollow.setCreatedTime(new Date());
            this.save(apUserFollow);

            //fan
            ApUserFan userFan = apUserFanService.getOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId)
                    .eq(ApUserFan::getFansId, userId));

            if (userFan == null){
                ApUserFan apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(userId.longValue());

                ApUser apUser = apUserService.getById(userId);
                if (apUser != null){
                    apUserFan.setFansName(apUser.getName());
                }

                apUserFan.setLevel((short)0);
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsShieldComment(false);
                apUserFan.setCreatedTime(new Date());
                apUserFanService.save(apUserFan);

                FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
                followBehaviorDto.setArticleId(articleId);
                followBehaviorDto.setFollowId(followId);
                followBehaviorDto.setUserId(userId);
                kafkaTemplate.send("followBehavior", JSON.toJSONString(followBehaviorDto));
                System.out.println("用户关注行为"+JSON.toJSONString(followBehaviorDto));


            }

        }else {
            flag = false;
        }


        return flag;
    }


}
